package com.light.applet.oauth.authentication;

import com.light.applet.oauth.service.WechatOauthService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author 魏彪
 */
public class WechatAuthenticationProvider implements AuthenticationProvider {

    private final UserDetailsService userDetailsService;

    public WechatAuthenticationProvider(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 先将authentication转为我们自定义的Authentication对象
        WechatAuthenticationToken authenticationToken = (WechatAuthenticationToken) authentication;
        // 获取微信登录码
        String code = (String) authenticationToken.getPrincipal();
        // 注册用户
        WechatOauthService detailsService = (WechatOauthService) userDetailsService;
        UserDetails userDetails = detailsService.loadUserByCode(code);
        // 返回认证成功的对象
        return new WechatAuthenticationToken(userDetails.getAuthorities(), userDetails);
    }


    /**
     * ProviderManager 选择具体Provider时根据此方法判断
     * 判断 authentication 是不是 <code>AbstractAuthenticationToken</code> 的子类或子接口
     */
    @Override
    public boolean supports(Class<?> authentication) {
        // isAssignableFrom方法如果比较类和被比较类类型相同，或者是其子类、实现类，返回true
        return WechatAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
